package io.seata.samples.integration.call.service;

//import io.seata.core.context.RootContext;
import com.google.protobuf.Empty;
import io.seata.samples.integration.common.dto.BusinessDTO;
import io.seata.samples.integration.common.dto.CommodityDTO;
import io.seata.samples.integration.common.dto.OrderDTO;
import io.seata.samples.integration.common.enums.RspStatusEnum;
import io.seata.samples.integration.common.exception.DefaultException;
import io.seata.samples.integration.common.order.OrderRequest;
import io.seata.samples.integration.common.order.OrderResponse;
import io.seata.samples.integration.common.order.OrderSummaryResponse;
import io.seata.samples.integration.common.response.ObjectResponse;
import io.seata.samples.integration.common.storage.GreeterGrpc;
import io.seata.samples.integration.common.storage.StorageLeftResponse;
import io.seata.samples.integration.common.storage.StorageRequest;
import io.seata.samples.integration.common.storage.StorageResponse;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: lidong
 * @Description  Dubbo业务发起方逻辑
 * @Date Created in 2019/9/5 18:36
 */
@Service
@Slf4j
public class BusinessServiceImpl implements BusinessService{

    @GrpcClient("storage-grpc-server")
    private GreeterGrpc.GreeterBlockingStub storageDubboService;

    @GrpcClient("order-grpc-server")
    private io.seata.samples.integration.common.order.GreeterGrpc.GreeterBlockingStub orderDubboService;

    boolean flag;

    /**
     * 处理业务逻辑 正常的业务逻辑
     * @Param:
     * @Return:
     */
//    @GlobalTransactional(timeoutMills = 300000, name = "dubbo-gts-seata-example")
    @Override
    public ObjectResponse handleBusiness(BusinessDTO businessDTO) {
//        log.info("开始全局事务，XID = " + RootContext.getXID());
        ObjectResponse<Object> objectResponse = new ObjectResponse<>();
        //1、扣减库存

        StorageRequest storageRequest = StorageRequest.newBuilder()
                .setCommodityCode(businessDTO.getCommodityCode())
                .setCount(businessDTO.getCount())
                .build();
        StorageResponse storageResponse = storageDubboService.decreaseStorage(storageRequest);
        //2、创建订单
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setUserId(businessDTO.getUserId());
        orderDTO.setCommodityCode(businessDTO.getCommodityCode());
        orderDTO.setOrderCount(businessDTO.getCount());
        orderDTO.setOrderAmount(businessDTO.getAmount());

        OrderRequest orderRequest = OrderRequest.newBuilder()
                .setUserId(businessDTO.getUserId())
                .setCommodityCode(businessDTO.getCommodityCode())
                .setOrderCount(businessDTO.getCount())
                .setOrderAmount(businessDTO.getAmount().longValue())
                .build();
        OrderResponse orderResponse = orderDubboService.createOrder(orderRequest);

        if (storageResponse.getStatus() != 200 || orderResponse.getStatus() != 200) {
            throw new DefaultException(RspStatusEnum.FAIL);
        }

        objectResponse.setStatus(RspStatusEnum.SUCCESS.getCode());
        objectResponse.setMessage(RspStatusEnum.SUCCESS.getMessage());
//        objectResponse.setData(orderResponse.getData());
        return objectResponse;
    }



//    @GlobalTransactional(timeoutMills = 300000, name = "dubbo-gts-seata-example")
   /* @Override
    public ObjectResponse handleBusiness2(BusinessDTO businessDTO) {
//        log.info("开始全局事务，XID = " + RootContext.getXID());
        ObjectResponse<Object> objectResponse = new ObjectResponse<>();
        //1、扣减库存
        CommodityDTO commodityDTO = new CommodityDTO();
        commodityDTO.setCommodityCode(businessDTO.getCommodityCode());
        commodityDTO.setCount(businessDTO.getCount());
        ObjectResponse storageResponse = storageDubboService.decreaseStorage(commodityDTO);
        //2、创建订单
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setUserId(businessDTO.getUserId());
        orderDTO.setCommodityCode(businessDTO.getCommodityCode());
        orderDTO.setOrderCount(businessDTO.getCount());
        orderDTO.setOrderAmount(businessDTO.getAmount());
        ObjectResponse<OrderDTO> response = orderDubboService.createOrder(orderDTO);

//        打开注释测试事务发生异常后，全局回滚功能
        if (!flag) {
            throw new RuntimeException("测试抛异常后，分布式事务回滚！");
        }

        if (storageResponse.getStatus() != 200 || response.getStatus() != 200) {
            throw new DefaultException(RspStatusEnum.FAIL);
        }

        objectResponse.setStatus(RspStatusEnum.SUCCESS.getCode());
        objectResponse.setMessage(RspStatusEnum.SUCCESS.getMessage());
        objectResponse.setData(response.getData());
        return objectResponse;
    }*/

    @Override
    public ObjectResponse summary() {
        StorageLeftResponse storage = storageDubboService.getStorage(Empty.newBuilder().build());
        OrderSummaryResponse ordersSum = orderDubboService.getOrdersSum(Empty.newBuilder().build());

        ObjectResponse objectResponse = new ObjectResponse();
        HashMap<String, Object> result = new HashMap<>();

        HashMap<String, Object> order_messages = new HashMap<>();
        order_messages.put("用户 1 账户余额", ordersSum.getLeft());
        order_messages.put("此商品共卖出单数",ordersSum.getTotal());
        result.put("此商品库存",(int)storage.getLeft());
        result.put("order messages",order_messages);

        objectResponse.setData(result);
        return objectResponse;
    }
}
